package com.sgcc.pda.greendao.model;

import com.sgcc.pda.baselibrary.log.HzLogSaveUtil;
import com.sgcc.pda.greendao.GreendaoManager;
import com.sgcc.pda.greendao.entity.SharepreferenceInfo;
import com.sgcc.pda.greendao.entity.SharepreferenceInfoDao;

import org.greenrobot.greendao.AbstractDao;

/**
 * Created by cj on 2020/8/22.
 * SHAREPREFERENCE_INFO 表的操作方法
 */
public class SharePreferenceModel extends HZBaseSqliteModel<Long, SharepreferenceInfo> {

    @Override
    protected AbstractDao<SharepreferenceInfo, Long> initDao() {
        HzLogSaveUtil.saveLog("sharePreferenceModel初始化时，daoSession==" + GreendaoManager.getInstance().getDaoSession().toString(), HzLogSaveUtil.LogType.DATABASE);
        return GreendaoManager.getInstance().getDaoSession().getSharepreferenceInfoDao();
    }


    /**
     * 重写插入，因为没有主键,会出现插入多条的情况。
     * 需要先查再存。
     */
    public long insertInfo(SharepreferenceInfo entity) {
        String editorKey = entity.getEditorKey();
        String key = entity.getKey();
        SharepreferenceInfo info = queryAndUnique(SharepreferenceInfoDao.Properties.EditorKey.eq(editorKey), SharepreferenceInfoDao.Properties.Key.eq(key));
        if (null == info) {
            return insert(entity);
        } else {
            info.setEditorKey(entity.getEditorKey());
            info.setEditorMode(entity.getEditorMode());
            info.setKey(entity.getKey());
            info.setType(entity.getType());
            info.setValue(entity.getValue());
            return update(info);
        }
    }

    /**
     * 根据editorKey和key查询String类型的值
     */
    public String queryString(String editorKey, String key) {
        SharepreferenceInfo info = queryAndUnique(SharepreferenceInfoDao.Properties.EditorKey.eq(editorKey), SharepreferenceInfoDao.Properties.Key.eq(key));
        if (info != null) {
            return info.getValue();
        }
        return "";
    }

    /**
     * 根据editorKey和key查询int类型的值
     */
    public int queryInt(String editorKey, String key) {
        SharepreferenceInfo info = queryAndUnique(SharepreferenceInfoDao.Properties.EditorKey.eq(editorKey), SharepreferenceInfoDao.Properties.Key.eq(key));
        if (info != null) {
            return Integer.parseInt(info.getValue());
        }
        return -1;
    }
}
